"""
时间相关任务模块
日期: 2024/12/19
"""

import utime
from machine import RTC

from supports.my_datetime import months_eng_short, weekdays_eng_short, utime_to_rtc, rtc_to_utime
from settings import ProductionConfig as current_config


class TaskTime():
    def __init__(self, at):
        self.at = at
    
    def init(self):
        if self.at.ntp_config[0] == 0:  # 如果未设置ntp服务器,就设置
            self.at.set_ntp(current_config.NTP_SERVER_LIST)
                
    def get_network_time(self):
        """
        获取网络时间
        参数: 无
        返回: 是否成功, 时间戳
        """
        returned = self.at.get_time()
        if returned[0]:
            datetime_lst = returned[2]
            year = int(datetime_lst[4])
            month = months_eng_short.index(datetime_lst[1]) + 1
            day = int(datetime_lst[2])
            week = weekdays_eng_short.index(datetime_lst[0])
            
            time_lst = datetime_lst[3].split(':')
            hour = int(time_lst[0])
            minute = int(time_lst[1])
            second = int(time_lst[2])
            
            if year >= 2024:  # 有时会返回1970,剔除错误的
                # 调整,暂时加1秒
                timestamp = utime.mktime((year, month, day, hour, minute, second, week, 0)) + 1
                return True, timestamp
            
            else:
                print(f"获取的时间异常:{datetime_lst}")  # todo 记录错误
                return False, -1
            
        else: # 获取网络时间失败
            print(returned[1])  # todo 记录错误
            return False, -1
        
    # 校时
    def calibration_time(self):
        returned = self.get_network_time()
        if returned[0]:
            timestamp_network = returned[1]  # 网络时间戳
            
            rtc = RTC()
            time_tuple_local = rtc.datetime()  # 本地时间元组
            timestamp_local = utime.mktime(rtc_to_utime(time_tuple_local))  # 本地时间戳
            
            if abs(timestamp_local - timestamp_network) > 3: # 超过允许的误差,校时
                time_tuple_network = utime_to_rtc(utime.localtime(timestamp_network))
                rtc.datetime(time_tuple_network)
                print(f"校时成功:{time_tuple_network}, {timestamp_local}")
            else:
                print(f"无需校时")
                
            return True
            
        else:
            print(f"校时失败:{returned[1]}")
            return False  